<?php
class FriendrequestModel extends Zend_Db_Table_Abstract {
	
	protected $_name = 'friend_request';
	protected $_id = 'id';
	
	public function request($user_id,$friend_id){
		$model = new FriendrequestModel();
		$is_requested = $model->fetchRow($model->select()->where('from_id = '.$user_id)->where('to_id = '.$friend_id));
//		print_r($is_request);
		if ($is_requested){
			$data = array('number_request'=>($is_requested['number_request']+1),'status'=>1);
			$model->update($data,'from_id = '.$user_id.' AND to_id = '.$friend_id);
		}
		else{
			$data = array('from_id'=>$user_id,'to_id'=>$friend_id);
			$id = $model->insert($data);
		}
	}
	
	public function requesting($user_id,$friend_id){
		$model = new FriendrequestModel();
		$r = $model->fetchRow($model->select()->where('from_id = '.$user_id)->where('to_id = '.$friend_id));
		if ($r['status']==1) return $r['id'];
		else return 0;
	}
	
	public function listrequest($user_id){
		$db = Zend_Registry::get('connectDB');
		$select = $db->select()
					->from(array('r'=>'friend_request'),array('user_id'=>'r.from_id','id'=>'r.id'))
													
					->join(array('u'=>'user'),'u.id = r.from_id',array('username'=>'u.username',
																		'fullname'=>'u.fullname',
																		'avatar'=>'u.avatar'))
					->where('r.to_id ='.$user_id)
					->where('r.status = 1');
		$list = $db->fetchAll($select);
		return $list;
	}
	
	public function getrequestinfo($id){
		$model = new FriendrequestModel();
		$info = $model->fetchRow($model->select()->where('id ='.$id));
		return $info;	
	}
	
	public function deleterequest($id){
		$model	= new FriendrequestModel();
		$data = array('status'=>0);
		$model->update($data,'id = '.$id);			
	}
	
	public function getnumberrequest($user_id,$friend_id){
		$model = new FriendrequestModel();
		$info = $model->fetchRow($model->select()->where('from_id = '.$user_id)->where('to_id = '.$friend_id));
		return $info['number_request'];
	}
}